package com.ruoyi.order.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.google.common.hash.BloomFilter;
import com.ruoyi.order.bloonfilter.BlooInit;
import com.ruoyi.order.clients.CouponFeignCliest;
import com.ruoyi.order.clients.MenuFeignCliens;
import com.ruoyi.order.domain.*;
import com.ruoyi.order.mapper.TbOrderDetailsMapper;
import com.ruoyi.system.api.model.LoginUser;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.order.mapper.TbOrderMapper;
import com.ruoyi.order.service.ITbOrderService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-02-07
 */
@Service
public class TbOrderServiceImpl implements ITbOrderService 
{
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbOrderDetailsMapper tbOrderDetailsMapper;
    @Autowired
    CouponFeignCliest couponFeignCliest;
    @Autowired
    MenuFeignCliens menuFeignCliens;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    BlooInit blooInit;

    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public TbOrder selectTbOrderById(Long id)
    {
        return tbOrderMapper.selectTbOrderById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param tbOrder 订单
     * @return 订单
     */
    @Override
    public List<TbOrder> selectTbOrderList(TbOrder tbOrder)
    {
        return tbOrderMapper.selectTbOrderList(tbOrder);
    }

    /**
     * 新增订单
     * 
     * @param tbOrder 订单
     * @return 结果
     */
    @Override
    public int insertTbOrder(TbOrder tbOrder)
    {
        return tbOrderMapper.insertTbOrder(tbOrder);
    }

    /**
     * 修改订单
     * 
     * @param tbOrder 订单
     * @return 结果
     */
    @Override
    public int updateTbOrder(TbOrder tbOrder)
    {
        return tbOrderMapper.updateTbOrder(tbOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTbOrderByIds(Long[] ids)
    {
        return tbOrderMapper.deleteTbOrderByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteTbOrderById(Long id)
    {
        return tbOrderMapper.deleteTbOrderById(id);
    }


    @Override
    @GlobalTransactional
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int addOrder(OrderDTO orderDTO) {
        LoginUser loginUser = com.ruoyi.common.security.utils.SecurityUtils.getLoginUser();
        Integer cuserId = Math.toIntExact(loginUser.getUserid());

        TbOrder tbOrder = new TbOrder();
        tbOrder.setCuserId(Long.valueOf(cuserId));
        tbOrder.setCuserName(loginUser.getUsername());
        tbOrder.setOrderCreatorTime(new Date());
        tbOrder.setTableId(orderDTO.getTableId());
        tbOrder.setOrderType("未支付订单");
        tbOrderMapper.insertTbOrder(tbOrder);
        BloomFilter bloomFilter = blooInit.bloomFilter();
        boolean b = bloomFilter.mightContain(tbOrder.getId().toString());
        System.out.println(b);
        if(b){
            //在查一遍数据库 验证到底订单号到底是否存在
            return 0;
        }
        BigDecimal totoleamount = BigDecimal.ZERO;
        for (MenuDTO menu : orderDTO.getMenus()) {
            TbOrderDetails tbOrderDetails = new TbOrderDetails();
            tbOrderDetails.setOrderId(tbOrder.getId());
            tbOrderDetails.setMenuName(menu.getMenuName());
            tbOrderDetails.setMenuId(menu.getId());
            tbOrderDetails.setMenuQuantityNum(menu.getMenuCount());
            tbOrderDetails.setMenuPrice(menu.getMenuPrice());
            BigDecimal menuPrice = menu.getMenuPrice();
            BigDecimal menuCount = BigDecimal.valueOf(menu.getMenuCount());
            totoleamount=totoleamount.add(menuPrice.multiply(menuCount));
            //使用优惠卷
            if(menu.getCouponId()!=null){
                TbCoupon tbCoupon = couponFeignCliest.findcouponById(Long.valueOf(menu.getCouponId()));
                BigDecimal couponAmount = tbCoupon.getCouponAmount();
                totoleamount=totoleamount.subtract(couponAmount);
                System.out.println(couponAmount);
            }
            //减库存
            TbMenu byIdmenu = menuFeignCliens.findByIdmenu(menu.getId());
            byIdmenu.setMenuCount(byIdmenu.getMenuCount()-menu.getMenuCount());
            menuFeignCliens.updatemenu(byIdmenu);
            tbOrderDetailsMapper.insertTbOrderDetails(tbOrderDetails);
        }

        //总金额添加到订单
        tbOrder.setTotalAmount(String.valueOf(totoleamount));
        tbOrderMapper.updateTbOrder(tbOrder);
        //删除我的购物车"cart:" + cuserId
        Set keys = redisTemplate.opsForHash().keys("cart:" + cuserId);
        keys.forEach(keyId->{
            redisTemplate.opsForHash().delete("cart:"+cuserId,keyId);
        });
        return 0;
    }

    /**
     * 我的订单列表
     * @param cuserId
     * @return
     */
    @Override
    public List<TbOrder> myOrderList(Integer cuserId) {
        List<TbOrder> tbOrderList = tbOrderMapper.selectTbOrderBycuserId(cuserId);
        return tbOrderList;
    }


}
